package com.myshiro.config;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.SessionsSecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author Jane
 * @date 2024-06-12 16:22
 */

@Configuration
public class ShiroConfig {

    @Bean
    public MyShiroRealm getMyShiroRealm(){
        MyShiroRealm realm = new MyShiroRealm();
        //处理controller的密码
        //登录认证通过后,HashedCredentialsMatcher.doCredentialsMatch(token,info)
        //token 处理
        realm.setCredentialsMatcher(hashedCredentialsMatcher()); //设置密码匹配器为hash散列算法的密码匹配器
        return realm;
    }

    @Bean
    public SessionsSecurityManager getSecurityManager(){
        return new DefaultWebSecurityManager(getMyShiroRealm());
    }

    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(){
        ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
        factoryBean.setSecurityManager(getSecurityManager());

        //角色  权限
        LinkedHashMap<String,String> urlMaps = new LinkedHashMap<>();

        urlMaps.put("/css/**","anon"); //放行
        urlMaps.put("/js/**","anon"); //放行
        urlMaps.put("/toLogin","anon"); //放行
        urlMaps.put("/user/doLogin","anon"); //放行
        urlMaps.put("/403","anon"); //放行

      /*  urlMaps.put("/user/list","perms[用户列表]"); //放行
        urlMaps.put("/user/update","perms[用户修改]"); //认证
        urlMaps.put("/user/del","perms[用户删除]"); //认证
        urlMaps.put("/user/add","perms[用户添加]"); //认证*/

        urlMaps.put("/logout","logout"); //放行退出


        urlMaps.put("/**","authc"); //放行退出

        factoryBean.setLoginUrl("/toLogin"); //如果用户认证失败,就去到这个登录的页面
        //factoryBean.setSuccessUrl("/user/index");
        factoryBean.setUnauthorizedUrl("/403");

        factoryBean.setFilterChainDefinitionMap(urlMaps);

        return factoryBean;
    }

    @Bean
    public ShiroDialect shiroDialect(){
        return  new ShiroDialect();
    }


    @Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher(){
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
        matcher.setHashAlgorithmName("md5"); //制定加密算法
        matcher.setHashIterations(1024); //加密次数
        return matcher;
    }
}
